#!/bin/perl
#

sub _js_protect {
	use String::CRC32;
	my $r = shift;
	my $salt = shift;
	my $cookie_sign = int($r->variable("cookie_j_sign"));
	my $time = int(time/600);
	my $sign = crc32($salt.$time);
	my $post = 0;
	if ($sign != $cookie_sign){
		$r->send_http_header("text/html");
		my $code = _js_protect_code($sign);
		$r->print("<html><body>");
		$r->print("<script>d='';
_=+!+[];
${code}
if(f){d='-';}
for(i=s.length-1;i>=0;i--){d=d+s.charAt(i);}
document.cookie='j_sign='+d;
if(document.cookie.indexOf('j_sign='+d)!=-1){
window.location.reload(true);
}else{document.body.innerHTML = 'Enabled a cookie';}
</script><noscript>Enable a JavaScript</noscript></body></html>");
		return 200;
	}
	return 0;
}

sub _js_protect_code {
	my $m = shift;
	my $s = 1;
	my $f = 0;
	my $ret = '';
	if($m < 0) {
		$m = -$m;
		$ret .= "f=1;";
	}else{
		$ret .= "f=0;";
	}
	$ret .= "s=[]";
	my $a = {};
	$a->{0} = {     0 => "(_)",     1 => "(_++)",   -1 => "(_--)" };
	$a->{1} = {     0 => "(_+!+[])",        1 => "(++_)",   -1 => "(_--+!+[])" };
	$a->{2} = {     1 => "(++_+!+[])", 2 => "(_+=2)", 0 => "(_+!+[]-~[])" };
	$a->{3} = {     1 => "(++_+!+[]+!+[])" };
	$a->{4} = {     1 => "(++_+!+[]+!+[]+!+[])" };
	$a->{5} = {     1 => "(++_+!+[]-~[]+!+[]+!+[])" };
	$a->{-1} = {    -1 => "(--_)",  1 => "(_+++~[])", 0=> "(_+~[])" };
	$a->{-2} = {    -1 => "(--_-!+[])", -2 => "(_-=2)", 0 => "(_-!+[]+~[])" };
	$a->{-3} = {    -1 => "(--_-!+[]-!+[])" };
	$a->{-4} = {    -1 => "(--_-!+[]-!+[]-!+[])" };
	$a->{-5} = {    -1 => "(--_-!+[]-!+[]+~[]-!+[])" };

	do {
		my $i = $m % 10 ;
		$m = ($m - $i) / 10 ;
		if(exists($a->{$i-$s})) {
			my $k = rnd($a->{$i-$s}) ;
			$ret .= "+" . $a->{$i-$s}->{$k}  ;
			$s += $k ;
		}else{
			$s = int(rand(10)) ;
			if($s==0) {$i--} ;
			$ret .= "+(+!(_=$s)+$i)" ;
		}

	} until ( $m == 0 );
	return $ret . ";" ;
	sub rnd {
		my $ar = shift ;
		my @d = () ;
		my $i = 0 ;
		foreach my $re (keys(%{$ar})) {
			$d[$i++] = $re ;
		}
		return $d[int(rand($#d+1))] ;
	}


}
